<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9" />
		<title>Journey Planner</title>
		<!-- Styling for example container (NoteContainer & Logger)  -->
		<link rel="stylesheet" type="text/css" href="http://api.maps.nokia.com/2.0.0/playground/examples/exampleUi.css"/>
		<!-- By default we add ?kml=auto to load KML package when needed if you don't use KML remove it -->
		<script type="text/javascript" charset="UTF-8" src="http://api.maps.nokia.com/2.0.0/jsl.js?kml=auto"></script>
		<!-- JavaScript for example container (NoteContainer & Logger)  -->
		<script type="text/javascript" charset="UTF-8" src="http://api.maps.nokia.com/2.0.0/playground/examples/examplesUi.js"></script>
		<style type="text/css">
			html {
				overflow:hidden;
			}

			body {
				margin: 0;
				padding: 0;
				overflow: hidden;
			}

			#mapContainer {
				width: 100%;
				height: 100%;
				left: 0;
				top: 0;
				position: absolute;
			}
		</style>
	</head>
	<body>
		<div id="mapContainer"></div>
		<div id="uiContainer"></div>
		<script>
var loadingflag = <?php echo $new ?>;
var max_marker = 100;
var route_id = <?php echo $id ?>;
var journeyname = '<?php echo $journeyname ?>';
var route_path = '<?php echo $route ?>';
var mapContainer = document.getElementById("mapContainer");

var map = new nokia.maps.map.Display(mapContainer, {
	center: [23.13, 72.41],
	zoomLevel: 10,
	components: [
		new nokia.maps.map.component.ZoomBar(), 
		new nokia.maps.map.component.TypeSelector(),
		new nokia.maps.positioning.component.Positioning(),
		new nokia.maps.map.component.Behavior()
	]
});
var noteContainer = new NoteContainer({
	id: "movingUi",
	parent: document.getElementById("uiContainer"),
	title: "<?php if($journeyname==""){ echo "New Map";}else{echo $journeyname;} ?>",
	content:
		'Search: <input id="place" /><br /><input id="findRoute" role="button" type="button" value="Search Place"/><input id="saveRoute" role="button" type="button" value="Save Route"/><br /><br />Approx Distance:<span id="approxDist"></span><br /> <a href="/journeys/jlist">Back to routes</a>'
});
function ajaxTalk(save)
{
	var xmlhttp;
	if (window.XMLHttpRequest)
	  {// code for IE7+, Firefox, Chrome, Opera, Safari
	  xmlhttp=new XMLHttpRequest();
	  }
	else
	  {// code for IE6, IE5
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	  }
	xmlhttp.onreadystatechange=function()
	  {
	  if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
		if(save){
			route_id = parseInt(xmlhttp.responseText); 
			
			alert('Route has been successfully saved');	
			document.getElementsByClassName("title")[0].innerHTML = "<h1>"+journeyname+"</h1>";
		}//else
			//route_path = xmlhttp.responseText;
			//if(route_path.length>0)
			//alert('Route has been successfully loaded');
		}
	  }
	  if(save){
		xmlhttp.open("GET","/journeys/store/"+route_id+"/"+journeyname+"/"+escape(route_path),false);
        xmlhttp.send();
	  }else{
		//xmlhttp.open("GET","/journeys/store/"+route_id,false);
	   }
	
}

var searchTerm,
	resultSet,
	/* We define a proximity object which we will pass to the Search Manager
	 * to set the center of the search and the radius around that center
	 * in which we would like to perform the search
	 */
	proximity = {
		center: new nokia.maps.geo.Coordinate(52.51, 13.4),
		radius: 1500 // search radius defined in meters
	};

var searchManager = new nokia.maps.search.Manager();
searchManager.addObserver("state", function (observedManager, key, value) {
	// If the search  has finished we can process the results
	if (value == "finished") {
		// We check that at least one location has been found
		if (observedManager.locations.length > 0) {
			// Remove results from previous search from the map
			if (resultSet) map.objects.remove(resultSet);
			// Convert all found locations into a searchResultSet creating markers for every found location
			resultSet = (new nokia.maps.search.component.SearchResultSet(observedManager.locations)).container;
			// Next we add the marker(s) to the map's object collection so they will be rendered onto the map.
			//map.objects.add(resultSet);
			// We zoom the map to a view that encapsulates all the markers into map's viewport.
			map.zoomTo(resultSet.getBoundingBox(), false);
		}
	} else if (value == "failed") {
		alert("The search request failed.");
	}
});
var findRoute = document.getElementById('findRoute');
findRoute.onclick = function () {
    searchManager.search(document.getElementById('place').value);
}
var saveRoute = document.getElementById('saveRoute');
saveRoute.onclick = function () {
	while(journeyname=="")
	journeyname = prompt("Please enter Journey Name","");
	ajaxTalk(true);
};

var waypoints = new nokia.maps.routing.WaypointParameterList(),
	markers = [], 
	dragMarker = null,
	polyCounter = 0,
	mode = [{
		type: "fastestNow",
		transportModes: ["car"],
		options: ""
	}],
	route,
	dragRoutePending = false,
	dragRouteCanceled = false,
	routePolyline,
	dragRoutePolyline,
	arrayIndexOf = function (array, element) {
		for (var i = 0, l = array.length; i < l; i++) {
			if (array[i] == element) {
				return i;
			}
		}
		return -1;
	},
	mpp = {
		1: 50312,
		2: 25156,
		3: 12578,
		4: 6289,
		5: 3145,
		6: 1572,
		7: 786,
		8: 393,
		9: 197,
		10: 98,
		11: 49,
		12: 25,
		13: 12,
		14: 6,
		15: 3,
		16: 2,
		17: 1,
		18: 1,
		19: 1,
		20: 1,
		21: 1,
		22: 1,
		23: 1
	},
	router = new nokia.maps.routing.Manager(),
	routerDrag = new nokia.maps.routing.Manager(), 
	updateRoute = function (oldValue, newValue) {
		if (markers.length > 1) {
			waypoints.coords = [];
				if(loadingflag==false){
					route_path = "";
				}
				distance = 0;
			for (var i = 0; i < markers.length; i++) {
				waypoints.coords.push(markers[i].coordinate);
				if(loadingflag==false){
					route_path += i.toString()+"la~"+markers[i].coordinate.latitude+";"+i.toString()+"lo~"+markers

[i].coordinate.longitude+";;";
				try{
				distance += waypoints.coords[i].distance(waypoints.coords[i-1]);
				}catch(e){}
				}
			}
			if(distance>0){
				distance = parseInt(distance / 1000);
			}
			document.getElementById("approxDist").innerHTML = distance.toString() + " KM";
			max_marker = markers.length;
			loadingflag=false;
			router.clear();
			router.calculateRoute(waypoints, mode.slice(0)); //pass a copy of the mode
		}
	}, 
	dragRoute = function (marker, newCoord) {
		dragRouteCanceled = false;
		if (!dragRoutePending && markers.length > 1) {
			dragRoutePending = true;
			var currentMarkerIdx = arrayIndexOf(markers, marker);

			if (markers.length == 2) {
				if (currentMarkerIdx == 0) {
					waypoints.coords = [newCoord, markers[1].coordinate];
				} else {
					waypoints.coords = [markers[0].coordinate, newCoord];
				}
			} else {
				if (markers.length > 2) {
					if (currentMarkerIdx == 0) {
						waypoints.coords = [newCoord, markers[1].coordinate];
					} else 
						if (currentMarkerIdx == (markers.length - 1)) {
							waypoints.coords = [markers[(currentMarkerIdx - 1)].coordinate, newCoord];
						} else {
							waypoints.coords = [markers[(currentMarkerIdx - 1)].coordinate, newCoord, markers[(currentMarkerIdx + 

1)].coordinate];
						}
				}
			}
			routerDrag.clear();

			var currentViewBounds = map.getViewBounds();
			routerDrag._additionalParams["viewbounds"] = "" + currentViewBounds.topLeft.latitude + "," + currentViewBounds.topLeft.longitude + 

";" + currentViewBounds.bottomRight.latitude + "," + currentViewBounds.bottomRight.longitude;
			routerDrag._additionalParams["resolution"] = "" + mpp[map.zoomLevel];
			routerDrag.calculateRoute(waypoints, mode.slice(0)); // Pass a copy of the modes
		}
	}, 
	updateRouteHandler = function (obj, prop, newValue) {
		if (newValue == "finished") {
			dragRouteCanceled = true;
			dragRoutePending = false;

			if (routePolyline) 
				routeLayer.objects.remove(routePolyline);

			route = obj.routes[0];
			routePolyline = new nokia.maps.map.Polyline(route.shape, {
				pen: {
					lineWidth: 6,
					lineJoin: 'round'
				}
			});

			routePolyline.addListener("mouseenter", function (evt) {
				var coord = map.pixelToGeo((evt.displayX - 8), (evt.displayY - 8));
				routerHoverMarker.set("coordinate", coord);
				routerHoverMarker.set("visibility", true);
			});
			routePolyline.addListener("mouseleave", function (evt) {
				routerHoverMarker.set("visibility", false);
			});

			if (dragRoutePolyline) 
				routeLayer.objects.remove(dragRoutePolyline);

			routeLayer.objects.add(routePolyline);
		}
	}, 
	dragRouteHandler = function (obj, prop, newValue) {
		if (newValue == "finished") {
			dragRoutePending = false;
			if (!dragRouteCanceled) {

				if (dragRoutePolyline) {
					routeLayer.objects.remove(dragRoutePolyline);
				}

				route = obj.routes[0];
				dragRoutePolyline = new nokia.maps.map.Polyline(route.shape, {
					pen: {
						lineWidth: 5,
						strokeColor: "#00FF0099",
						lineJoin: 'round'
					}
				});

				routeLayer.objects.add(dragRoutePolyline);
			}
		}
	};

router.addObserver("state", updateRouteHandler, router);
routerDrag.addObserver("state", dragRouteHandler, routerDrag);
routerDrag._responseattributes = "";
routerDrag._routeattributes = "waypoints";
routerDrag._maneuverattributes = "";
routerDrag._additionalParams = {};
routerDrag._additionalParams["representation"] = "dragNDrop";

var createWaypointMarker = function (geocoord, index) {
	var marker = new nokia.maps.map.StandardMarker(geocoord, {
		draggable: true,
		visibility: false
	});

	// Add a listener for click events on waypoint markers
	marker.addListener("click", function (evt) {
		if (evt.ctrlKey) {
			// Remove the waypoint marker from the map and recalculate the route
			removeWaypointMarker(evt.currentTarget);
			updateRoute();
			evt.preventDefault();
			evt.stopPropagation();
		}
	});

	// Add a listener for drag events on waypoint markers
	marker.addListener("drag", function (evt) {
		if (Math.abs(evt.deltaX) > 3 || Math.abs(evt.deltaY) > 3) {
			var coord = map.pixelToGeo(evt.displayX, evt.displayY);
			dragRoute(this, coord);
		}
	});
	// Add a listener for dragend events on waypoint markers
	marker.addListener("dragend", function (evt) {
		updateRoute();
	});

	// Add the marker to the markers array according to the passed index
	if (typeof index == "number") {
		markers.splice(index, 0, marker);
	} else {
		markers.push(marker);
		index = markers.length;
	}

	// Correct the markers' text after maker insertion
	for (var i = (index - 1); i < markers.length; i++) {
		markers[i].set("text", "" + (i + 1));
	}

	// Add marker to the markerLayer, to make it visible on the map
	markerLayer.objects.add(marker);

	return marker;
};

// Method which removes waypoint markers from the map
var removeWaypointMarker = function (marker) {
	var index = arrayIndexOf(markers, marker);

	markers.splice(index, 1);
	markerLayer.objects.remove(marker);

	// Correct the markers' text after maker insertion
	for (var i = index; i < markers.length; i++) {
		markers[i].set("text", "" + (i + 1));
	}

	// Remove the route if there aren't more than 1 marker left
	if (markers.length < 2) {
		// remove the current route polyline from the map
		if (routePolyline) 
			routeLayer.objects.remove(routePolyline);
	}
};

// Create a layer for the route shape objects
var routeLayer = new nokia.maps.map.Container();
map.objects.add(routeLayer);

var routeHoverContext = new nokia.maps.gfx.Graphics();
routeHoverContext.beginImage(18, 18);
routeHoverContext.set("fillColor", "#FFF2");
routeHoverContext.set("strokeColor", "#000");
routeHoverContext.set("lineWidth", 2);
routeHoverContext.drawEllipse(1, 1, 14, 14);
routeHoverContext.fill();
routeHoverContext.stroke();

var routerHoverMarker = new nokia.maps.map.Marker({
	latitude: 50,
	longitude: 50
}, {
	icon: new nokia.maps.gfx.GraphicsImage(routeHoverContext.getIDL()),
	visibility: false,
	anchor: new nokia.maps.util.Point(0, 0),
	draggable: true
});
routeLayer.objects.add(routerHoverMarker);

// Add the listener for the mouse move event on the route
routeLayer.addListener("mousemove", function (evt) {
	var coord = map.pixelToGeo((evt.displayX - 8), (evt.displayY - 8));
	routerHoverMarker.set("coordinate", coord);
});

// Add the listener for the dragstart event on the route
routerHoverMarker.addListener("dragstart", function (evt) {
	var coord = map.pixelToGeo(evt.displayX, evt.displayY), nearestIndex = routePolyline.getNearestIndex(coord), shape = routePolyline.path.asArray(), 

currentWaypoint = route.waypoints[0].mappedPosition, currentWaypointIdx = 0, i;

	// Find the route's waypoint which comes before the point affected by the dragstart operation
	for (i = 0; i <= ((nearestIndex + 1) * 3); i += 3) {
		if (currentWaypoint.latitude == shape[i] &&
		currentWaypoint.longitude == shape[i + 1]) {
			currentWaypoint = route.waypoints[++currentWaypointIdx].mappedPosition;
		}
	}

	// Create a new marker at the drag start position and add it to the markers array at the correct position
	dragMarker = createWaypointMarker(coord, currentWaypointIdx);
});

// Add the listener for the drag event on the route
routerHoverMarker.addListener("drag", function (evt) {
	if (Math.abs(evt.deltaX) > 3 || Math.abs(evt.deltaY) > 3) {
		var coord = map.pixelToGeo(evt.displayX, evt.displayY);

		// Drag the route
		dragRoute(dragMarker, coord);
	}
});

// Add the listener for the dragend event on the route
routerHoverMarker.addListener("dragend", function (evt) {
	var coord = map.pixelToGeo(evt.displayX, evt.displayY);

	// Finalize the new created drag marker
	dragMarker.set("coordinate", coord);
	dragMarker.set("visibility", true);
	// Update the whole route
	updateRoute();
});

// Create a layer for the waypoint markers
var markerLayer = new nokia.maps.map.Container();
map.objects.add(markerLayer);

// Add a listener for click events on the map for adding markers and triggering the route recalculation
map.addListener("click", function (evt) {
	if (evt.ctrlKey) {
		var coord = map.pixelToGeo(evt.displayX, evt.displayY);
		var marker = createWaypointMarker(coord);
		marker.set("visibility", true);
		updateRoute();
		evt.preventDefault();
	}
});
ajaxTalk(false);
if(loadingflag==true && route_path.length>0){
//alert(document.cookie);
loadingflag=false;
rp = route_path.split(';;');


	//Setting Up the points and paths :)
	for(var j=0;j<rp.length;j++){

	if(!rp[j])
		break;
	rp[j] = rp[j].split(';');

	if(!rp[j][0])
		break;

	rp[j][0] = rp[j][0].split('~');
	rp[j][1] = rp[j][1].split('~');

	var la=rp[j][0][1];
	var lo=rp[j][1][1];
	map.set("center", new nokia.maps.geo.Coordinate(parseFloat(la),parseFloat(lo)));
	var start = createWaypointMarker({
		latitude: parseFloat(la),
		longitude: parseFloat(lo)
	});

	start.set("visibility", true);

 	
	}
	loadingflag=false;
updateRoute();
}else{
//alert(document.cookie);
var start = createWaypointMarker({
		latitude: 23.14,
		longitude: 72.42
	});
	start.set("visibility", true);

var end = createWaypointMarker({
		latitude: 23.16,
		longitude: 72.40
	});
	end.set("visibility", true);
}
updateRoute();


 </script>
	</body>
</html>
